<?php
namespace app\controller;

use support\think\Cache;
use think\facade\Db;
use support\Request;
use support\View;
use zjkal\MysqlHelper;

class InstallController
{
    public function ajax(Request $request)
    {
        $file=base_path().'/tpl/'.'install.txt';
        if(file_exists($file)){
            return redirect('/index');
        }
        $data=$request->post();
        if(!isset($data['token']) or $data['token']!=Cache::get('tok')){
            return json(['code'=>0,'msg'=>'验证错误，请刷新页面，重新提交']);
        }
        error_reporting(1);
        $conn = new \mysqli('127.0.0.1', $data['user'], $data['pass']);
        if ($conn->connect_error) {
            return json(['code'=>0,'msg'=>'服务器账号秘密错误']);
        }
        if(!$conn->client_info){
            return json(['code'=>0,'msg'=>'服务器账号秘密错误']);
        }else{
            $data1=[];
            $result = \mysqli_query($conn,'show databases;');
            While($row = \mysqli_fetch_assoc($result)){
                $data1[] = $row['Database'];
            }
            unset($result, $row);
            \mysqli_close($conn);
            if(\in_array($data['data'],$data1)){
                return json(['code'=>1,'msg'=>'已经存在']);
            }else{
                return json(['code'=>2,'msg'=>'是否创建']);
            }
        }
    }
    public function chuang(Request $request)
    {
        $file=base_path().'/tpl/'.'install.txt';
        if(file_exists($file)){
            return redirect('/index');
        }
        $data=$request->post();
        if(!isset($data['token']) or $data['token']!= Cache::get('tok')){
            return json(['code'=>0,'msg'=>'验证错误，请刷新页面，重新提交']);
        }
        // 创建连接
        $conn = new \mysqli('127.0.0.1', $data['user'], $data['pass']);
        // 检测连接
        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }
        // 创建数据库
        $sql = "CREATE DATABASE ".$data['data'];
        if ($conn->query($sql) === TRUE) {
            $conn->close();
            return json(['code'=>1,'msg'=>'创建成功，请点击"导入数据"']);
        } else {
            $conn->close();
            return json(['code'=>0,'msg'=>'创建失败，请重试或者手动创建！']);
        }
    }
    public function index(Request $request)
    {
        $file=base_path().'/tpl/'.'install.txt';
        if(file_exists($file)){
            return redirect('/index');
        }
        if($request->method()=='POST'){
            $data=$request->post();
            if(!$data["database"] or !$data["username"] or !$data["password"]){
                return response('数据信息必须填写');
            }
            try{
                $mysql_server_name = '127.0.0.1'; //改成自己的mysql数据库服务器
                $mysql_username = $data["username"]; //改成自己的mysql数据库用户名
                $mysql_password = $data["password"]; //改成自己的mysql数据库密码
                $mysql_database = $data["database"]; //改成自己的mysql数据库名
                $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库
                mysqli_close($conn);
            }catch(\Exception $e){
                return response('数据信息不正确,请先验证数据库后提交！');
            }
            //还原数据库
            $dir=base_path().'/sql';
            $wo=scandir($dir);
            $sqlarr=[];
            foreach($wo as $k=>$v){
                if(\is_file($dir.'/'.$v)){
                    $sqlarr[filemtime($dir.'/'.$v)]=[
                        'dir'=>strtr($dir.'/'.$v, " \ ", " / "),
                        'name'=>$v,
                        'time'=>filemtime($dir.'/'.$v)
                    ];
                }
            }
            krsort($sqlarr);
            if(count($sqlarr)<=0){
                return response('找不到sql文件');
            }
            $new=array_shift($sqlarr);
            $mysql = new MysqlHelper();
            $mysql->setConfig(['username' => $data["username"], 'password' => $data["password"], 'database' => $data["database"]]);

            $conn = mysqli_connect('127.0.0.1', $data["username"], $data["password"], $data["database"]);
            if (!$conn) { e("连接失败: " . mysqli_connect_error());     }
            $result = mysqli_query($conn, "show tables");
            if ($result and mysqli_num_rows($result) > 0) {
                while($row = mysqli_fetch_assoc($result)) {
                    mysqli_query($conn, "drop table ".$row["Tables_in_".$data["database"]]);
                }
            }
            mysqli_close($conn);
            $wo=$mysql->importSqlFile($new['dir']);
           // $wo=$mysql->exportSqlFile($dir.'/'.date('Y-m-d-H-i-s').'.sql');
            //修改数据配置
            $app=config_path().'/thinkorm.php';

            $apphtml=file_get_contents($app);
            $apphtml=str_replace('rootroot',$data["password"],$apphtml);
            $apphtml=str_replace('root',$data["username"],$apphtml);
            $apphtml=str_replace('next',$data["database"],$apphtml);
            $apphtml=str_replace('_lizhili_database',$data["database"],$apphtml);
            $apphtml=str_replace('_lizhili_username',$data["username"],$apphtml);
            $apphtml=str_replace('_lizhili_password',$data["password"],$apphtml);
            file_put_contents($app,$apphtml);
            $file=base_path().'/tpl/'.'install.txt';
            file_put_contents($file,'lock:'.date('Y-m-d-H-i-s'));
            return redirect('/');

        }
        $tok=md5(time().mt_rand(1,9999));
        Cache::set('tok', $tok, 360);
        return view('install/install',[
            'tok'=>$tok
        ]);
    }


}
